﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Microsoft.SharePoint;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Text;

namespace WebCumpleanios
{
    public partial class Default : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                try
                {
                    DataTable _dt = new DataTable();
                    SqlConnection _cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnx1"].ToString());
                    SqlCommand _cmd = new SqlCommand();
                    _cmd.CommandType = CommandType.StoredProcedure;
                    _cmd.Connection = _cnn;
                    _cmd.CommandText = "proc_fechas";
                    _cmd.Parameters.Add(new SqlParameter("@idcurrentUser", hfIDcurrentUser.Value));
                    _cnn.Open();
                    _dt.Load(_cmd.ExecuteReader());
                    _cnn.Close();
                    setearGrilla(_dt);
                    ViewState["Dia"] = true;
                    ViewState["Fechas"] = _dt;
                    columnaDia();
                    hdEnlace.Value = ConfigurationManager.AppSettings["enlace"].ToString();//Enlace Plantilla

                    hdEnlace2.Value = ConfigurationManager.AppSettings["enlace2"].ToString();//Enlace FotoUsuario
                }
                catch (Exception)
                {

                    throw;
                }

            }
        }

        private void columnaDia()
        {
            DataTable _dt = (DataTable)ViewState["Fechas"];
            Boolean _dia = (Boolean)ViewState["Dia"];
            //GridView1.Columns[1].Visible = !_dia;

            if (_dia)
            {
                DataTable _dtFiltro = _dt.Copy();
                DataRow _newRow;
                _dtFiltro.Rows.Clear();
                DataRow[] _rows = _dt.Select("dia = " + DateTime.Now.Day.ToString(), "");

                foreach (DataRow _row in _rows)
                {
                    _newRow = _dtFiltro.NewRow();
                    _newRow["ID"] = _row["ID"];
                    _newRow["NombreSolo"] = _row["NombreSolo"];
                    _newRow["Nombre"] = _row["Nombre"];
                    _newRow["dia"] = _row["dia"];
                    _newRow["imagen"] = _row["imagen"];
                    _dtFiltro.Rows.Add(_newRow);
                }
                _dt = _dtFiltro;
                Button1.Text = "Ver las del Mes";
            }
            else
                Button1.Text = "Ver las de Hoy";

            setearGrilla(_dt);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Boolean _dia = (Boolean)ViewState["Dia"];
            if (_dia)
                ViewState["Dia"] = false;
            else
                ViewState["Dia"] = true;
            columnaDia();
        }

        private void setearGrilla(DataTable _dt)
        {
            //NameOrTitle
            SPWeb _web = obtenerWeb(ConfigurationManager.AppSettings["urlSite"].ToString());
            SPPictureLibrary libreriaImagenes = (SPPictureLibrary)_web.Lists[ConfigurationManager.AppSettings["lstFotos"].ToString()];
            String _html = @"<table cellpadding=""0"" cellspacing=""0"" style='width:100%;'>";
            int _dia = 0;
            foreach (DataRow _row in _dt.Rows)
            {
                _dia = int.Parse(_row["dia"] + "");
                _html = _html + @"<tr class=""fondoFila"">";
                _html = _html + @"<td  class=""nombrePersona""><img style='width:70px;height:80px;' src='" + obtenerFoto(libreriaImagenes, _row["ID"].ToString().Trim()) + "'/></td>";
                if (_dia >= DateTime.Now.Day)
                {
                    _html = _html + @"<td><div><a href=""javascript:mtenlace('" + Utils.Base64Encode(_row["ID"].ToString().Trim()) + @"','" + Utils.Base64Encode(_row["imagen"].ToString().Trim()) + @"');"" class=""enlace"">" + _row["Nombre"] + "</a><span style='display:block;'>" + _row["area"] +"</span><div></td>";
                }
                else
                    _html = _html + @"<td><div><span style='display:block;'>" + _row["Nombre"] + "</span><span style='display:block;'>" + _row["area"] + "</span></div></td>";
                _html = _html + @"</tr>";
                _html = _html + @"<tr>";
                _html = _html + @"<td colspan=""2"" style=""height:10px; color:White; font-size:4pt;"">...</td>";
                _html = _html + @"</tr>";
            }
            if (_dt.Rows.Count<1)
            {
            _html = _html + "<tr><td style='font-size: 11px;padding: 4px;color: #4B4B4B;'>No tenemos cumpleaños el día de hoy</td></tr>";    
            }
            _html = _html + "</table>";
            DIVListado.InnerHtml = _html;
            
            Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), Guid.NewGuid().ToString(), "resize();", true);
        }

        private Boolean archivoExiste(String _file)
        {
            Boolean _resp = false;
            _resp = File.Exists(Server.MapPath(_file));
            return _resp;
        }

        private String obtenerFoto(SPPictureLibrary _libreriaImagenes, String user)
        {
            String _urlImagen = "images/camera.png";
            DataTable _dt = _libreriaImagenes.Items.GetDataTable();
            DataRow[] _rows = _dt.Select("NameOrTitle like '" + user.ToLower() + ".%'", "");
            if (_rows.Length > 0)
            {
                _urlImagen = "/" + _rows[0]["RequiredField"] + "";
                _dt.Dispose();
            }
            return _urlImagen;
        }

        private SPWeb obtenerWeb(String _siteURL)
        {
            //SPSite _site = new SPSite(_siteURL);
            //SPWeb _web = _site.OpenWeb();
            //SPUser _user = _web.AllUsers[ConfigurationManager.AppSettings["pImpersonalizacion"]];
            //SPUserToken mitoken = _user.UserToken;
            //_site = new SPSite(_siteURL, mitoken);
            //_web = _site.OpenWeb();
            //return _web;
            SPWeb spWeb = null;
            SPSecurity.RunWithElevatedPrivileges(delegate
            {
                using (SPSite sitio = new SPSite(_siteURL))
                {
                    spWeb = sitio.OpenWeb();
                }
            });

            return spWeb;
        }
    }
}